package com.speljohan.rsbot.gui;

import java.awt.BorderLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import com.speljohan.rsbot.script.Script;

public class PauseScriptSelector extends JDialog implements ActionListener {
	private static final long serialVersionUID = -3060364633238608218L;

	public boolean isOkay = false;

	private final Map<Integer, Script> runningScripts;

	private JTable scriptTable;

	public PauseScriptSelector(final Window parent,
			final Map<Integer, Script> runningScripts) {
		super(parent, "Running Scripts", ModalityType.APPLICATION_MODAL);
		this.runningScripts = runningScripts;
		initializeGUI();
	}

	public void actionPerformed(final ActionEvent e) {
		final String command = e.getActionCommand().intern();
		if (command == "Cancel") {
			dispose();
		} else if (command == "OK") {
			isOkay = true;
			dispose();
		} else {
			throw new RuntimeException(command);
		}
	}

	public int getSelectedScript() {
		return (Integer) scriptTable
		.getValueAt(scriptTable.getSelectedRow(), 0);
	}

	public void initializeGUI() {
		final JButton okButton = new JButton("OK");
		final JButton cancelButton = new JButton("Cancel");

		okButton.addActionListener(this);
		cancelButton.addActionListener(this);

		final JPanel buttonPanel = new JPanel();
		buttonPanel.setBorder(null);
		buttonPanel.add(okButton);
		buttonPanel.add(cancelButton);

		scriptTable = new JTable(loadTableModel());
		scriptTable.setBorder(null);
		scriptTable.setAutoCreateRowSorter(true);
		final JScrollPane scriptScroller = new JScrollPane(scriptTable);
		scriptScroller.setBorder(null);

		add(scriptScroller);
		add(buttonPanel, BorderLayout.SOUTH);

		pack();
		setLocationRelativeTo(getOwner());
	}

	private TableModel loadTableModel() {
		final Vector<Vector<Comparable<?>>> rows = new Vector<Vector<Comparable<?>>>(
				runningScripts.size());
		for (final Integer id : runningScripts.keySet()) {
			final Script s = runningScripts.get(id);
			final Vector<Comparable<?>> v = new Vector<Comparable<?>>();
			v.add(id);
			v.add(s.getName());
			v.add(s.getAuthor());
			v.add(s.getVersion());
			v.add(s.isPaused);
			rows.add(v);
		}
		final Vector<String> cols = new Vector<String>();
		cols.add("ID");
		cols.add("Name");
		cols.add("Author");
		cols.add("Version");
		cols.add("Paused");
		return new DefaultTableModel(rows, cols);
	}

	/**
	 * True is the user hits okay and they have selected a script.
	 */
	public boolean showToUser() {
		setVisible(true);
		return isOkay && scriptTable.getSelectedRow() != -1;
	}
}
